/*
 * @Descripttion: 
 * @version: 
 * @Author: chenWeiLong
 * @Date: 2022-02-18 19:07:09
 * @LastEditors: please set LastEditors
 * @LastEditTime: 2022-03-12 16:07:37
 */
import { createApp, toRaw } from "vue";
import App from "./App.vue";
import "./assets/css/reset.less";
import Card from "./components/card.vue";
import router from "./router/router";
import ElementPlus from "element-plus";
import "element-plus/theme-chalk/index.css";
import zhCn from "element-plus/es/locale/lang/zh-cn"; //引入中文包
import * as Icons from "@element-plus/icons-vue";
import { createPinia, PiniaPluginContext } from "pinia"; //引入pinia
// import { getStorage, setStorage } from "./utils/cook"

import Loading from "./views/plugin/index"  // 引入loading


const app = createApp(App);
/**
 * pinia数据持久化封装***********************************
 */
const setStorage = (key: string, value: any) => {
  return localStorage.setItem(key, JSON.stringify(value));
}
const getStorage = (key: string) => {
  return localStorage.getItem(key) ? JSON.parse(localStorage.getItem(key) as string) : {};
}



const _pininaKey = 'piniaKey'

const pinia = createPinia();

type Options = {
  key?: string
}
const piniaPlugin = (options: Options) => {
  return (context: PiniaPluginContext) => {
    const { store } = context;
    const data = getStorage(`${options?.key ?? _pininaKey}_${store.$id}`);
    // state的变化时触发
    store.$subscribe(() => {
      console.log(store, 'state变化了');
      // toRaw 将proxy代理对象转化为原始对象
      setStorage(`${options?.key ?? _pininaKey}_${store.$id}`, toRaw(store.$state))
    })

    return {
      ...data,
    }
  }
}

pinia.use(piniaPlugin({
  key: 'pinia'
}));





/**
 * pinia数据持久化封装***********************************
 */

type Filter = {
  format: <T extends any>(str: T) => T
}
// 声明要扩充@vue/runtime-core包的声明.
// 这里扩充"ComponentCustomProperties"接口, 因为他是vue3中实例的属性的类型.
declare module "@vue/runtime-core" {
  export interface ComponentCustomProperties {
    //申明 解决页面引用报错问题
    $filters: Filter,
    $$loading: {
      show: () => void,
      hide: () => void
    }
  }
}


// 挂载全局变量
app.config.globalProperties.$filters = {
  format<T>(str: T): string {
    return '真 · ' + str
  }
}

app
  .use(ElementPlus, { locale: zhCn })
  .use(pinia)
  .use(Loading) //使用loading 插件
  .use(router)
  .component("Card", Card)
  .mount("#app");

const Person = {
  name: "小陈",
  age: 27,
};
type tp = typeof Person;
type keys = keyof tp;

// console.log(keys);
// typeof获取一个对象的类型
// keyof 获取某种类型的所有键(key),返回的是一个联合类型
// 全局注册Icons
Object.keys(Icons).forEach((key) => {
  app.component(key, Icons[key as keyof typeof Icons]);
});



